import { animateCreater } from "./animateCreater";
import {  wukong } from "./character";

let targetX: number = 0,//相机x
    targetY: number = 53;//相机y

const state: any = { // 存储任意状态
    isLeft: false,
    isRight: false,
    playerAnimation: 'stand',
};

// 由于统一了键盘和虚拟按键，所以二者都是改上方state的值
// let w: Phaser.Input.Keyboard.Key,//键盘按键
//     s: Phaser.Input.Keyboard.Key,
//     a: Phaser.Input.Keyboard.Key,
//     d: Phaser.Input.Keyboard.Key;

const button: any = {}; // 按钮对象实体

let update = gameloop1;//循环

let ground: Phaser.GameObjects.Group,
    background: Phaser.GameObjects.Sprite;

let player: Phaser.Types.Physics.Arcade.SpriteWithDynamicBody;

let wukong0:any;
const config: Phaser.Types.Core.GameConfig = {
    type: Phaser.AUTO,
    parent: 'phaser-example',
    width: 192,
    height: 108,
    zoom: 6,//关于整个canvas的缩放
    // pixelArt: true,
    physics: {
        default: 'arcade',
    },
    scene: {
        preload: preload,
        create: create,
        update: update
    }
};

const game = new Phaser.Game(config);


function preload(this: Phaser.Scene) {
    console.log("preload");
    this.load.multiatlas('all', 'assets/all.json', 'assets');
    this.load.multiatlas('jiaotou', 'assets/jiaotou.json', 'assets');
    this.load.multiatlas('langbin', 'assets/langbin.json', 'assets');
    this.load.multiatlas('pang', 'assets/pang.json', 'assets');
    this.load.multiatlas('ui', 'assets/ui.json', 'assets');
    this.load.multiatlas('wukong', 'assets/wukong.json', 'assets');
}

function create(this: Phaser.Scene) {
    console.log("create");

    // this.cameras.main.setBounds(0, 0, 1520, 108);//摄像机的边界。

    this.cameras.main.setZoom(1);//设置变焦值，相当于镜头远近。

    // this.cameras.main.centerOn(targetX, targetY);//移动摄像机的位置

    // 处理键盘交互事件
    dealKeyBoard.bind(this)();

    // background
    background = this.add.sprite(0, -1, "all", "大地图.png").setOrigin(0, 0);

    // ground
    ground = this.physics.add.staticGroup();
    let g1 = ground.create(0, 96, "all", "地板.png");
    g1.x = 760;

    // 主角
    player = this.physics.add.sprite(0, 0, "wukong", "站1.png");//暂时以站1.png为体积。
    player.setBounce(0.2);
    // player.setCollideWorldBounds(true);
    player.body.setGravityY(300);

    var zhan = this.anims.generateFrameNames('wukong', {//这动画创建比pixi还麻烦
        start: 1, end: 2, zeroPad: 1,
        prefix: '站', suffix: '.png'
    });//动画创建详情https://www.codeandweb.com/texturepacker/tutorials/how-to-create-sprite-sheets-for-phaser3
    this.anims.create({ key: 'stand', frames: zhan, frameRate: 10, repeat: -1 });

    player.anims.play('stand');//动画和角色不存在绑定关系，。

    var zhan = this.anims.generateFrameNames('wukong', {
        start: 1, end: 5, zeroPad: 1,
        prefix: '走', suffix: '.png'
    });
    this.anims.create({ key: 'walk', frames: zhan, frameRate: 10, repeat: -1 });

    this.physics.add.collider(player, ground);//计算玩家与地板碰撞

    this.physics.world.createDebugGraphic();//显示物体碰撞边界（debug用）

    addUI.bind(this)();

    animateCreater.setup(this);

    wukong0=new wukong(this,0,0,ground);
    wukong0.beginsayhi();
    setTimeout(()=>{wukong0.stopsayhi();},2000);

}

// 尽量减少在loop代码
function gameloop1(this: Phaser.Scene) {
    if ( state.isLeft) {
        player.x--;
    } else if ( state.isRight) {
        player.flipX = false;
        player.x++;
    }
    this.cameras.main.centerOnX(player.x);
}

function addUI(this: Phaser.Scene) {
    // 显示(非交互)
    button.health0 = this.add.sprite(2, 2, 'ui', '血1.png').setOrigin(0, 0).setScrollFactor(0);
    button.health1 = this.add.sprite(9, 2, 'ui', '血1.png').setOrigin(0, 0).setScrollFactor(0);
    button.health2 = this.add.sprite(16, 2, 'ui', '血1.png').setOrigin(0, 0).setScrollFactor(0);

    // 按钮
    button.left = this.add.sprite(6, 90, "ui", "左键.png").setOrigin(0, 0).setScrollFactor(0).setData('buttonInfo', 'left').setInteractive();
    button.right = this.add.sprite(25, 90, "ui", "右键.png").setOrigin(0, 0).setScrollFactor(0).setData('buttonInfo', 'right').setInteractive();
    button.j = this.add.sprite(160, 95, 'ui', 'j键2.png').setOrigin(0, 0).setScrollFactor(0).setData('buttonInfo', 'j').setInteractive();
    button.k = this.add.sprite(170, 95, 'ui', 'k键2.png').setOrigin(0, 0).setScrollFactor(0).setData('buttonInfo', 'k').setInteractive();
    button.l = this.add.sprite(180, 95, 'ui', 'l键2.png').setOrigin(0, 0).setScrollFactor(0).setData('buttonInfo', 'l').setInteractive();
    button.o = this.add.sprite(160, 80, 'ui', 'u键2.png').setOrigin(0, 0).setScrollFactor(0).setData('buttonInfo', 'u').setInteractive();
    button.u = this.add.sprite(170, 80, 'ui', 'i键2.png').setOrigin(0, 0).setScrollFactor(0).setData('buttonInfo', 'i').setInteractive();
    button.i = this.add.sprite(180, 80, 'ui', 'o键2.png').setOrigin(0, 0).setScrollFactor(0).setData('buttonInfo', 'o').setInteractive();


    const onIconDown = function (pointer: any, gameObject: Phaser.GameObjects.GameObject) {
        console.log(gameObject.getData('buttonInfo'))
        switch (gameObject.getData('buttonInfo')) {
            case 'left':
                state.isLeft = true;
                player.flipX = true;
                player.anims.play('walk');
                break;
            case 'right':
                state.isRight = true;
                player.flipX = false;
                player.anims.play('walk');
                break
            default:
                break;
        }
    }
    const onIconUpOut = function (pointer: any, gameObject: Phaser.GameObjects.GameObject) {
        console.log(gameObject.getData('buttonInfo'))
        switch (gameObject.getData('buttonInfo')) {
            case 'left':
                state.isLeft = false;
                player.anims.play('stand');
                break;
            case 'right':
                state.isRight = false;
                player.anims.play('stand');
                break
            default:
                break;
        }
    }
    this.input.on('gameobjectdown', onIconDown, this);
    this.input.on('gameobjectout', onIconUpOut, this);
    this.input.on('gameobjectup', onIconUpOut, this);
}

function dealKeyBoard(this: Phaser.Scene) {
    this.input.keyboard.addCapture('W,S,A,D');
    this.input.keyboard.addKey('W');
    this.input.keyboard.addKey('S');
    this.input.keyboard.addKey('A');
    this.input.keyboard.addKey('D');

    this.input.keyboard.on('keydown', function (event: any) {
        switch (event.key) {
            case 'a':
                state.isLeft = true;
                player.flipX = true;
                player.anims.play('walk');
                break;
            case 'd':
                state.isRight = true;
                player.flipX = false;
                player.anims.play('walk');
                break;
            default:
                break;
        }
    })

    this.input.keyboard.on('keyup', function (event: any) {
        switch (event.key) {
            case 'a':
                state.isLeft = false;
                player.anims.play('stand');
                break;
            case 'd':
                state.isRight = false;
                player.anims.play('stand');
                break;
            default:
                break;
        }
    })
}
